package com.csdig.html.dao.impl;

import com.csdig.cms.dao.UserDao;
import com.csdig.db.DBUtils;
import com.csdig.db.model.Sql;
import com.csdig.html.dao.ForumPostDao;
import com.csdig.html.model.ForumPost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author wei_jc
 * @since 1.0.0
 */
@Repository
public class ForumPostDaoImpl implements ForumPostDao {
    @Autowired
    private UserDao userDao;

    @Override
    public void add(ForumPost vo) throws Exception {
        Sql sql = new Sql("insert into forum_post(subject,user_id,content,create_date,click_count) values(:subject,:user_id,:content,now(),0)");
        sql.set("subject", vo.getSubject());
        if (vo.getUser() != null) {
            sql.set("user_id", vo.getUser().getId());
        }
        sql.set("content", vo.getContent());
        DBUtils.exeUpdate(sql);
    }

    @Override
    public void update(ForumPost vo) throws Exception {

    }

    @Override
    public void delete(int postId) throws Exception {

    }

    @Override
    public ForumPost findById(int postId) throws Exception {
        String sql = "select * from forum_post where post_id=?";
        return DBUtils.queryBean(sql, ForumPost.class, postId);
    }

    @Override
    public List<ForumPost> findByCondition(ForumPost vo) throws Exception {
        Sql sql = new Sql("select * from forum_post where 1=1 ");
        // /add condtion here
        List<ForumPost> result = DBUtils.queryBeanList(sql, ForumPost.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (ForumPost post : result) {
            post.setUser(userDao.findById(post.getUserId()));
            post.setReplayCount(0);
            post.setLastReplayDate(sdf.format(post.getCreateDate()));
        }
        return result;
    }

    @Override
    public List<ForumPost> listAll() throws Exception {
        return findByCondition(null);
    }
}
